using System;
using System.Data;
using System.Data.SqlClient;
using Csla;
using Csla.Data;
using Csla.Validation;
using BA.DAL;
using BA;
using System.Text;

namespace BlazeApps.Library.Links
{
    [Serializable()]
    public class LinksDetail : Csla.BusinessBase<LinksDetail>
    {
        private BlazeApps.Library.ConfigSettings Config = new BlazeApps.Library.ConfigSettings();
        private BA.DAL.DBUtility DAL = new BA.DAL.DBUtility();
        private Procedures Procs = new Procedures();

        #region Business Properties and Methods

        //declare members
        private Guid _linkid = Guid.NewGuid();
        private string _linktitle = string.Empty;
        private string _linkurl = string.Empty;
        private string _linkdesc = string.Empty;
        private Guid _userid = Guid.Empty;
        private SmartDate _createdate = new SmartDate(DateTime.Today);

        [System.ComponentModel.DataObjectField(true, false)]
        public Guid Linkid
        {
            get
            {
                CanReadProperty("Linkid", true);
                return _linkid;
            }
        }

        public string Linktitle
        {
            get
            {
                CanReadProperty("Linktitle", true);
                return _linktitle;
            }
            set
            {
                CanWriteProperty("Linktitle", true);
                if (value == null) value = string.Empty;
                if (!_linktitle.Equals(value))
                {
                    _linktitle = value;
                    PropertyHasChanged("Linktitle");
                }
            }
        }

        public string Linkurl
        {
            get
            {
                CanReadProperty("Linkurl", true);
                return _linkurl;
            }
            set
            {
                CanWriteProperty("Linkurl", true);
                if (value == null) value = string.Empty;
                if (!_linkurl.Equals(value))
                {
                    _linkurl = value;
                    PropertyHasChanged("Linkurl");
                }
            }
        }

        public string Linkdesc
        {
            get
            {
                CanReadProperty("Linkdesc", true);
                return _linkdesc;
            }
            set
            {
                CanWriteProperty("Linkdesc", true);
                if (value == null) value = string.Empty;
                if (!_linkdesc.Equals(value))
                {
                    _linkdesc = value;
                    PropertyHasChanged("Linkdesc");
                }
            }
        }

        public Guid Userid
        {
            get
            {
                CanReadProperty("Userid", true);
                return _userid;
            }
            set
            {
                CanWriteProperty("Userid", true);
                if (!_userid.Equals(value))
                {
                    _userid = value;
                    PropertyHasChanged("Userid");
                }
            }
        }

        public DateTime Createdate
        {
            get
            {
                CanReadProperty("Createdate", true);
                return _createdate.Date;
            }
        }

        public string CreatedateString
        {
            get
            {
                CanReadProperty("CreatedateString", true);
                return _createdate.Text;
            }
            set
            {
                CanWriteProperty("CreatedateString", true);
                if (value == null) value = string.Empty;
                if (!_createdate.Equals(value))
                {
                    _createdate.Text = value;
                    PropertyHasChanged("CreatedateString");
                }
            }
        }

        protected override object GetIdValue()
        {
            return _linkid;
        }

        #endregion //Business Properties and Methods

        #region Validation Rules
        private void AddCustomRules()
        {
            //add custom/non-generated rules here...
        }

        private void AddCommonRules()
        {
            //
            // Linktitle
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "Linktitle");
            //
            // Linkurl
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "Linkurl");
            //
            // Createdate
            //
            ValidationRules.AddRule(CommonRules.StringRequired, "CreatedateString");
        }

        protected override void AddBusinessRules()
        {
            AddCommonRules();
            AddCustomRules();
        }
        #endregion //Validation Rules

        #region Authorization Rules
        protected override void AddAuthorizationRules()
        {
            //TODO: Define authorization rules in LinksDetail
            //AuthorizationRules.AllowRead("Linkid", "LinksDetailReadGroup");
            //AuthorizationRules.AllowRead("Linktitle", "LinksDetailReadGroup");
            //AuthorizationRules.AllowRead("Linkurl", "LinksDetailReadGroup");
            //AuthorizationRules.AllowRead("Linkdesc", "LinksDetailReadGroup");
            //AuthorizationRules.AllowRead("Userid", "LinksDetailReadGroup");
            //AuthorizationRules.AllowRead("Createdate", "LinksDetailReadGroup");
            //AuthorizationRules.AllowRead("CreatedateString", "LinksDetailReadGroup");

            //AuthorizationRules.AllowWrite("Linktitle", "LinksDetailWriteGroup");
            //AuthorizationRules.AllowWrite("Linkurl", "LinksDetailWriteGroup");
            //AuthorizationRules.AllowWrite("Linkdesc", "LinksDetailWriteGroup");
            //AuthorizationRules.AllowWrite("Userid", "LinksDetailWriteGroup");
            //AuthorizationRules.AllowWrite("CreatedateString", "LinksDetailWriteGroup");
        }


        public static bool CanGetObject()
        {
            //TODO: Define CanGetObject permission in LinksDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("LinksDetailViewGroup"))
            //	return true;
            //return false;
        }

        public static bool CanAddObject()
        {
            //TODO: Define CanAddObject permission in LinksDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("LinksDetailAddGroup"))
            //	return true;
            //return false;
        }

        public static bool CanEditObject()
        {
            //TODO: Define CanEditObject permission in LinksDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("LinksDetailEditGroup"))
            //	return true;
            //return false;
        }

        public static bool CanDeleteObject()
        {
            //TODO: Define CanDeleteObject permission in LinksDetail
            return true;
            //if (Csla.ApplicationContext.User.IsInRole("LinksDetailDeleteGroup"))
            //	return true;
            //return false;
        }
        #endregion //Authorization Rules

        #region Factory Methods
        private LinksDetail()
        { /* require use of factory method */ }

        public static LinksDetail NewLinksDetail()
        {
            if (!CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a LinksDetail");
            return DataPortal.Create<LinksDetail>();
        }

        public static LinksDetail GetLinksDetail(Guid linkid)
        {
            if (!CanGetObject())
                throw new System.Security.SecurityException("User not authorized to view a LinksDetail");
            return DataPortal.Fetch<LinksDetail>(new Criteria(linkid));
        }

        public static void DeleteLinksDetail(Guid linkid)
        {
            if (!CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a LinksDetail");
            DataPortal.Delete(new Criteria(linkid));
        }

        public override LinksDetail Save()
        {
            if (IsDeleted && !CanDeleteObject())
                throw new System.Security.SecurityException("User not authorized to remove a LinksDetail");
            else if (IsNew && !CanAddObject())
                throw new System.Security.SecurityException("User not authorized to add a LinksDetail");
            else if (!CanEditObject())
                throw new System.Security.SecurityException("User not authorized to update a LinksDetail");

            return base.Save();
        }

        #endregion //Factory Methods

        #region Data Access

        #region Criteria

        [Serializable()]
        private class Criteria
        {
            public Guid Linkid;

            public Criteria(Guid linkid)
            {
                this.Linkid = linkid;
            }
        }

        #endregion //Criteria

        #region Data Access - Create
        [RunLocal]
        protected override void DataPortal_Create()
        {
            ValidationRules.CheckRules();
        }

        #endregion //Data Access - Create

        #region Data Access - Fetch
        private void DataPortal_Fetch(Criteria criteria)
        {
            ExecuteFetch(criteria);
        }

        private void ExecuteFetch(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            DAL.AddParameter("@linkid", criteria.Linkid);

            using(SafeDataReader dr = new SafeDataReader(DAL.ExecuteReader(Procs.GetLinkByLinkID.ToString().Trim(), CommandType.Text, ConnectionState.Open)))
            {
                FetchObject(dr);
                ValidationRules.CheckRules();

                //load child object(s)
                FetchChildren(dr);
            }
        }

        private void FetchObject(SafeDataReader dr)
        {
            dr.Read();
            _linkid = dr.GetGuid("linkid");
            _linktitle = dr.GetString("linktitle");
            _linkurl = dr.GetString("linkurl");
            _linkdesc = dr.GetString("linkdesc");
            _userid = dr.GetGuid("userid");
            _createdate = dr.GetSmartDate("createdate", _createdate.EmptyIsMin);
        }

        private void FetchChildren(SafeDataReader dr)
        {
        }
        #endregion //Data Access - Fetch

        #region Data Access - Insert
        protected override void DataPortal_Insert()
        {
            ExecuteInsert();
        }

        private void ExecuteInsert()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddInsertParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.InsertLink.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddInsertParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@linkid", _linkid);
            DAL.AddParameter("@linktitle", _linktitle);
            DAL.AddParameter("@linkurl", _linkurl);
            if (_linkdesc.Length > 0)
                DAL.AddParameter("@linkdesc", _linkdesc);
            else
                DAL.AddParameter("@linkdesc", DBNull.Value);
            DAL.AddParameter("@userid", _userid);
            DAL.AddParameter("@createdate", _createdate.DBValue);
        }
        #endregion //Data Access - Insert

        #region Data Access - Update
        protected override void DataPortal_Update()
        {
            if (base.IsDirty)
            {
                ExecuteUpdate();
            }
        }

        private void ExecuteUpdate()
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddUpdateParameters(ref DAL);

            DAL.ExecuteNonQuery(Procs.UpdateLink.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddUpdateParameters(ref BA.DAL.DBUtility DAL)
        {
            DAL.AddParameter("@linkid", _linkid);
            DAL.AddParameter("@linktitle", _linktitle);
            DAL.AddParameter("@linkurl", _linkurl);
            if (_linkdesc.Length > 0)
                DAL.AddParameter("@linkdesc", _linkdesc);
            else
                DAL.AddParameter("@linkdesc", DBNull.Value);
            DAL.AddParameter("@userid", _userid);
            DAL.AddParameter("@createdate", _createdate.DBValue);
        }

        private void UpdateChildren(SqlConnection cn)
        {
        }
        #endregion //Data Access - Update

        #region Data Access - Delete
        protected override void DataPortal_DeleteSelf()
        {
            DataPortal_Delete(new Criteria(_linkid));
        }

        private void DataPortal_Delete(Criteria criteria)
        {
            ExecuteDelete(criteria);
        }

        private void ExecuteDelete(Criteria criteria)
        {
            DAL.CreateDBObjects(Config.ConnectionString, Config.Provider);

            AddDeleteParameters(ref DAL, criteria);

            DAL.ExecuteNonQuery(Procs.DeleteLink.ToString().Trim(), CommandType.Text, ConnectionState.Open);
        }

        private void AddDeleteParameters(ref BA.DAL.DBUtility DAL, Criteria criteria)
        {
            DAL.AddParameter("@linkid", criteria.Linkid);
        }
        #endregion //Data Access - Delete
        #endregion //Data Access
    }
}
